package com.apptonelabs.vphonevisor.netty;
/*
 * Copyright NetEnrich, Inc. All rights reserved. NetEnrich
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

import static org.jboss.netty.channel.Channels.pipeline;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLEngine;

import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;

import com.apptonelabs.vphonevisor.netty.ssl.TLSsslContextFactory;

public class VPhoneVisorProtocolCodecFactory implements ChannelPipelineFactory {
    private Timer timer = null;
    private ChannelHandler idleStateHandler;
    
    public VPhoneVisorProtocolCodecFactory() {
		if(timer == null)
			timer = new HashedWheelTimer();
		
		if(idleStateHandler == null)
			idleStateHandler = new IdleStateHandler(timer, 180, 180, 180, TimeUnit.MINUTES);
    }
    
    public VPhoneVisorProtocolCodecFactory(Timer timer) {
        this.timer = timer;
        this.idleStateHandler = new IdleStateHandler(timer, 180, 180, 180, TimeUnit.MINUTES);
    }
	
	@Override
	public ChannelPipeline getPipeline() throws Exception {
		ChannelPipeline pipeline = pipeline();
		
		if(timer == null)
			timer = new HashedWheelTimer();
		
		if(idleStateHandler == null)
			idleStateHandler = new IdleStateHandler(timer, 180, 180, 180, TimeUnit.MINUTES);

		// Idle Timer
		pipeline.addLast("timeout", idleStateHandler);
		
        // Uncomment the following line if you want HTTPS
        SSLEngine engine = TLSsslContextFactory.getServerContext().createSSLEngine();
        engine.setUseClientMode(false);
        pipeline.addLast("ssl", new SslHandler(engine));

        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("encoder", new HttpResponseEncoder());
        pipeline.addLast("deflater", new HttpContentCompressor());
        pipeline.addLast("handler", new HttpRequestHandler());
        
		return pipeline;
	}
}
